import request from './request'
import auth from '../utils/auth'

// 默认导出对象
export default {
    // 登录
    login(data) {
        return request.post('/user/login', data)
    },

    // 注册
    register(data) {
        return request.post('/user/register', data)
    },

    // 聊天（流式）
    chatStream(prompt, conversationId = 'default-conversation', onMessageChunk, onComplete, onError) {
        const url = `http://localhost:8080/ai/chat?prompt=${encodeURIComponent(prompt)}&conversationId=${encodeURIComponent(conversationId)}`;
        const token = auth.getToken();

        fetch(url, {
            method: 'GET',
            headers: {
                'Authorization': token ? `Bearer ${token}` : ''
            }
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let accumulatedResponse = '';

                function readStream() {
                    reader.read().then(({ done, value }) => {
                        if (done) {
                            onComplete(accumulatedResponse);
                            return;
                        }

                        const chunk = decoder.decode(value, { stream: true });
                        accumulatedResponse += chunk;
                        onMessageChunk(chunk);
                        readStream();
                    }).catch(error => {
                        onError(error);
                    });
                }

                readStream();
            })
            .catch(error => {
                onError(error);
            });
    },

    // 清除聊天历史
    clearChatHistory(conversationId = 'default-conversation') {
        return request.get('/ai/clear-history', {
            params: {
                conversationId
            }
        })
    },

    // 根据ID查询用户信息
    getUserById(id) {
        return request.get('/user/selectById', {
            params: {
                id
            }
        })
    },
    
    // 根据ID查询用户信息（通过/id接口）
    getId(userId) {
        return request.get('/user/id', {
            params: {
                userId
            }
        })
    },
    
    // 分页查询用户
    getUserPage(pageNum = 1, pageSize = 10, userId = '', userName = '') {
        return request.get('/user/page', {
            params: {
                pageNum,
                pageSize,
                userId,
                userName
            }
        })
    },
    
    // 更新用户信息
    updateUser(user) {
        return request.put('/user/update', user)
    }
}

// 同时提供命名导出，以便People.vue组件使用
export function getUserPage(pageNum = 1, pageSize = 10, userId = '', userName = '') {
  return request.get('/user/page', {
    params: {
      pageNum,
      pageSize,
      userId,
      userName
    }
  })
}

export function updateUser(user) {
  return request.put('/user/update', user)
}

export function getUserById(id) {
  return request.get('/user/selectById', {
    params: {
      id
    }
  })
}